package utils

import (
	"crypto/rand"
	"encoding/base64"
	"math/big"
)

const (
	letterBytes   = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	letterIdxBits = 6                    // 6 bits to represent a letter index
	letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
)

// GenerateString 生成指定长度的随机字符串
func GenerateString(length int) string {
	b := make([]byte, length)
	for i := 0; i < length; {
		if idx, err := rand.Int(rand.Reader, big.NewInt(int64(len(letterBytes)))); err == nil {
			b[i] = letterBytes[idx.Int64()]
			i++
		}
	}
	return string(b)
}

// GenerateToken 生成安全的随机token
func GenerateToken(length int) string {
	b := make([]byte, length)
	if _, err := rand.Read(b); err != nil {
		return ""
	}
	return base64.URLEncoding.EncodeToString(b)[:length]
}

// 字符串截取
func TruncateString(str string, length int) string {
	runeStr := []rune(str)
	if len(runeStr) > length {
		return string(runeStr[:length])
	}
	return str
}

func IsStringInSlice(target string, slice []string) bool {
	for _, item := range slice {
		if item == target {
			return true
		}
	}
	return false
}
